package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.entity.AddressEntity;
import com.chexiehui.jc.widget.LoadingLayout;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Author: SongJun.
 * CreateDate: 2019/2/22 0022.
 * Description: 地址选择
 */

public class MapChooseActivity extends BaseActivity implements OnGetGeoCoderResultListener, BaiduMap.OnMapStatusChangeListener, BaiduMap.OnMapClickListener {

    @BindView(R.id.mv_map_view)
    MapView mMapView;
    @BindView(R.id.tv_address_description)
    TextView mTvAddressDescription;
    private boolean isFirstLoc = true; // 是否首次定位

    private AddressEntity mAddressEntity;

    private BaiduMap mBaiduMap;
    private MyLocationData locData;
    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用

    @Override
    protected void setTitleBar() {
        titleBar.setDividerVisible(false)
                .setLeftTextDrawable(R.drawable.ic_svg_back)
                .setStatusBarLightMode(true)
                .setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent));
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_map_choose;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mAddressEntity = (AddressEntity) bundle.getSerializable("entity");
        }
        if (mAddressEntity == null) mAddressEntity = new AddressEntity();
    }

    @Override
    protected void initView(Bundle var1) {
        mBaiduMap = mMapView.getMap();
        //隐藏地图上百度地图logo图标
        mMapView.removeViewAt(1);
        //隐藏地图上比例尺
        mMapView.showScaleControl(false);
        //隐藏缩放按钮
        mMapView.showZoomControls(false);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        mBaiduMap.setOnMapStatusChangeListener(this);
        mBaiduMap.setOnMapClickListener(this);

        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        if (mAddressEntity != null) {
            centerToLatLng(mAddressEntity.getLat(), mAddressEntity.getLng());
            mTvAddressDescription.setText(mAddressEntity.getAddressAll());
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        applyLocationPermission();
    }

    @OnClick({R.id.iv_my_location,
            R.id.tv_address_sure,})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_my_location:
                if (locData != null) {
                    centerToLatLng(locData.latitude, locData.longitude);
                    geoLatLng(locData.latitude, locData.longitude);
                }
                break;
            case R.id.tv_address_sure:
                if (mAddressEntity.getLat() <= 0 || mAddressEntity.getLng() <= 0) {
                    return;
                }
                Intent data = new Intent();
                data.putExtra("address", mAddressEntity);
                setResult(RESULT_OK, data);
                onBackPressed();
                break;
        }
    }

    private void geoLatLng(double lat, double lng) {
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(lat, lng)).newVersion(1).radius(100));
    }

    private void centerToLatLng(double lat, double lng) {
        LatLng ll = new LatLng(lat, lng);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll).zoom(16.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (mMapView == null) return;
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            showToast("抱歉，未能找到结果");
            if (mAddressEntity.getLat() > 0 && mAddressEntity.getLng() > 0) {
                centerToLatLng(mAddressEntity.getLat(), mAddressEntity.getLng());
            }
            return;
        }
        mAddressEntity.setLat(result.getLocation().latitude);
        mAddressEntity.setLng(result.getLocation().longitude);
        mAddressEntity.setProvince(result.getAddressDetail().province);
        mAddressEntity.setCity(result.getAddressDetail().city);
        mAddressEntity.setDistrict(result.getAddressDetail().district);

        mAddressEntity.setDestinationAddress(result.getAddressDetail().town + result.getAddressDetail().street +
                (result.getPoiList() == null || result.getPoiList().size() < 1 ? "" : result.getPoiList().get(0).name));
        mTvAddressDescription.setText(mAddressEntity.getAddressAll());
        LogUtils.e("GeoCodeDemo", "ReverseGeoCodeResult = " + result.toString());
    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        if (isFirstLoc) {
            return;
        }
        geoLatLng(mapStatus.target.latitude, mapStatus.target.longitude);
    }

    @Override
    public void onMapClick(LatLng latLng) {
        centerToLatLng(latLng.latitude, latLng.longitude);
        geoLatLng(latLng.latitude, latLng.longitude);
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        centerToLatLng(mapPoi.getPosition().latitude, mapPoi.getPosition().longitude);
        geoLatLng(mapPoi.getPosition().latitude, mapPoi.getPosition().longitude);
        return false;
    }

    private void applyLocationPermission() {
        AndPermission.with(this)
                .permission(Permission.LOCATION)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        if (!AppApplication.getInstances().getLocationService().isStart()) {
                            AppApplication.getInstances().getLocationService().start();
                        }
                        AppApplication.getInstances().getLocationService().registerListener(mListener);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            // 第一种：用默认的提示语。
                            AndPermission.defaultSettingDialog(MapChooseActivity.this, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            ToastUtils.showShort("请在权限管理中开启位置权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_LOACTION)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).show();
                    }
                }).start();
    }

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LogUtils.e("home-----------------:" + location.getAddrStr());
                if(!StringUtils.isTrimEmpty(location.getCity())){
                    Message msg = new Message();
                    msg.obj = location;
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }

        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                BDLocation location = (BDLocation) msg.obj;
                locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(location.getRadius()).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                if (isFirstLoc) {
                    isFirstLoc = false;
                    if (mAddressEntity.getLat() <= 0 || mAddressEntity.getLng() <= 0) {
                        centerToLatLng(location.getLatitude(), location.getLongitude());
                        geoLatLng(location.getLatitude(), location.getLongitude());
                    } else {
                        centerToLatLng(mAddressEntity.getLat(), mAddressEntity.getLng());
                        mTvAddressDescription.setText(mAddressEntity.getAddressAll());
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        handler.removeCallbacksAndMessages(null);
        handler = null;
        AppApplication.getInstances().getLocationService().unregisterListener(mListener);
        mListener = null;
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }
}
